package com.hw.one.dam2.controller;

import com.hw.one.core.controller.BaseController;
import com.hw.one.core.result.MsgResult;
import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.entity.AIREntity;
import com.hw.one.dam2.ledVideo.EnvDataPO;
import com.hw.one.dam2.po.PatrolDevicePO;
import com.hw.one.dam2.service.*;
import com.hw.one.dam2.util.ExcelUtil;
import com.hw.one.dam2.util.ResponseUtil;
import com.hw.one.util.DateTimeUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/06/13 13:49.
 * <p>
 * 不用登陆就可以访问的Controller
 */
@RestController
@RequestMapping(value = "noAuthen")
public class NoAuthenticationFilterController extends BaseController {

    @Autowired
    private IMonitorDeviceService monitorDeviceService;

    @Autowired
    private IWeatherService weatherService;

    @Autowired
    private IAirService airService;

    @Autowired
    private IPatrolDeviceService patrolDeviceService;

    @Autowired
    private IQuartzService quartzService;

    /**
     * 查询移动监测设备数据
     *
     * @param request
     * @return
     * @author 李亚坤
     * @createtime 2017年6月15日16:16:01
     */
    @RequestMapping(value = "findDataListBySnCode", method = RequestMethod.GET)
    public MsgResult findDataListBySnCode(HttpServletRequest request) {
        try {
            String snCode = request.getParameter("snCode");
            if (StringUtils.isEmpty(snCode)) {
                return MsgResult.errorResult("设备编码不能为空");
            }
            Map<String, Object> resultMap = monitorDeviceService.findDataListBySnCode(snCode);
            return MsgResult.okResult(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询移动监测设备数据异常,后台异常", e);
            return MsgResult.errorResult();
        }
    }


    /**
     * 测试西安市 推送数据方法类
     */
    @RequestMapping(value = "pullXiAnData", method = RequestMethod.GET)
    public MsgResult pullXiAnData(HttpServletRequest request) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("siteCode", "4100000009179009"); // 渭南市 西大明路A6C2701009
            EnvDataPO envData = weatherService.findCityLiveWeatherByRegionCodeTwo(paramMap);//.getLEDData(null);

            log.info("--------------------------------");
            return MsgResult.okResult(envData);
        } catch (Exception e) {
            log.error("测试推送数据错误", e);
        }
        return MsgResult.errorResult();
    }

    /**
     * 测试西安市 保存推送数据方法类
     */
    @RequestMapping(value = "saveXiAnData", method = RequestMethod.GET)
    public void saveXiAnData(HttpServletRequest request) {
        try {
            quartzService.saveScreenDataPullData();
        } catch (Exception e) {
            log.error("测试保存推送数据错误", e);
        }
    }

    /**
     * 根据区域编码、时间和表名查询出空气质量数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "findAirByRegionCodesAndTime", method = RequestMethod.GET)
    public MsgResult findAirByRegionCodesAndTime(HttpServletRequest request) {
        try {
            // 查询的编码组 410100052,410100051
            String checkedRegionCodes = request.getParameter("queryCheckCode");
            if (StringUtils.isEmpty(checkedRegionCodes)) {
                return MsgResult.errorResult("区域编码不能为空");
            }
            // 2017-06-22 20:00:00
            String startTime = request.getParameter("startTime");
            if (StringUtils.isEmpty(startTime)) {
                return MsgResult.errorResult("开始时间不能为空");
            }
            // 2017-06-22 20:00:00
            String endTime = request.getParameter("endTime");
            if (StringUtils.isEmpty(endTime)) {
                return MsgResult.errorResult("结束时间不能为空");
            }
            // 查询的表名（全称） T_DATA_REGION_AIR_HOUR
            String tableName = request.getParameter("tableName");
            if (StringUtils.isEmpty(tableName)) {
                return MsgResult.errorResult("表名不能为空");
            }
            // 封装request中的查询条件
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("checkedRegionCodes", checkedRegionCodes);
            paraMap.put("tableName", tableName);
            paraMap.put("startTime", startTime);
            paraMap.put("endTime", endTime);

            List<AIREntity> resultMap = airService.findAirDataByRegionCodesAndTime(paraMap);
            return MsgResult.okResult(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询空气质量数据信息异常,后台异常", e);
            return MsgResult.errorResult();
        }
    }

    /**
     * 根据区域编码、时间和表名查询出空气质量数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "findAirBySiteCodesAndTime", method = RequestMethod.GET)
    public MsgResult findAirBySiteCodesAndTime(HttpServletRequest request) {
        try {
            // 查询的编码组 411327000,520300000
            String checkedSiteCodes = request.getParameter("queryCheckCode");
            if (StringUtils.isEmpty(checkedSiteCodes)) {
                return MsgResult.errorResult("站点编码不能为空");
            }
            // 2017-06-22 20:00:00
            String startTime = request.getParameter("startTime");
            if (StringUtils.isEmpty(startTime)) {
                return MsgResult.errorResult("开始时间不能为空");
            }
            // 2017-06-22 20:00:00
            String endTime = request.getParameter("endTime");
            if (StringUtils.isEmpty(endTime)) {
                return MsgResult.errorResult("结束时间不能为空");
            }
            // 查询的表名（全称） T_DATA_AIR_HOUR
            String tableName = request.getParameter("tableName");
            if (StringUtils.isEmpty(tableName)) {
                return MsgResult.errorResult("表名不能为空");
            }
            // 封装request中的查询条件
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("checkedSiteCodes", checkedSiteCodes);
            paraMap.put("tableName", tableName);
            paraMap.put("startTime", startTime);
            paraMap.put("endTime", endTime);

            List<AIREntity> resultMap = airService.findAirDataBySiteCodesAndTime(paraMap);
            return MsgResult.okResult(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询空气质量数据信息异常,后台异常", e);
            return MsgResult.errorResult();
        }
    }

    /**
     * 导出空气质量数据Excel表格
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "airQualityDataReportExportExcel", method = RequestMethod.GET)
    public void airQualityDataReportExportExcel(HttpServletRequest request, HttpServletResponse response) {
        Workbook wb;
        try {
            // 站点数组/区域数组 默认：siteCodeType
            String checkCodeType = request.getParameter("checkCodeType");
            if (null == checkCodeType || "".equals(checkCodeType)) {
                checkCodeType = "siteCodeType";
            }
            // 站点数组/区域数组 默认：空
            String queryCheckCode = request.getParameter("queryCheckCode");
            if (null == queryCheckCode || "".equals(queryCheckCode)) {
                queryCheckCode = "";
            }
            String tableName = request.getParameter("tableName");
            // 查询的表名，默认：空
            if (null == tableName || "".equals(tableName)) {
                tableName = "";
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            // 开始时间
            String startTime = request.getParameter("startTime");
            startTime = null == startTime || "".equals(startTime)
                ? DateTimeUtil.getFormatDateStr(calendar.getTime(), DamConstant.SDF_YMD_HMS) : startTime;
            // 结束时间
            String endTime = request.getParameter("endTime");
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            endTime = null == endTime || "".equals(endTime)
                ? DateTimeUtil.getFormatDateStr(calendar.getTime(), DamConstant.SDF_YMD_HMS) : endTime;

            // 封装request中的查询条件
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("tableName", tableName);
            paraMap.put("startTime", startTime);
            paraMap.put("endTime", endTime);
            List<AIREntity> aqiList = null;
            if ("siteCodeType".equals(checkCodeType)) {
                paraMap.put("checkedSiteCodes", queryCheckCode);
                aqiList = airService.findAirDataBySiteCodesAndTime(paraMap);
            } else {
                paraMap.put("checkedRegionCodes", queryCheckCode);
                aqiList = airService.findAirDataByRegionCodesAndTime(paraMap);
            }


            wb = ExcelUtil.fillAirReportDataExcelWithTemplate(aqiList, "aqiDataReportTemplate.xlsx",
                tableName + " " + startTime + "--" + endTime + "空气质量数据");

            ResponseUtil.export(response, wb, "Mongo空气质量数据.xlsx");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出空气质量数据Excel异常,后台异常", e);
        }

    }

    /**
     * 空气质量数据对比趋势（将站点和区域合并为一个接口）
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "findAirQualityContrastThrend", method = RequestMethod.GET)
    public MsgResult findAirQualityContrastThrend(Model model, HttpServletRequest request) {
        // 站点数组/区域数组 默认：siteCodeType
        String checkCodeType = request.getParameter("checkCodeType");
        if (null == checkCodeType || "".equals(checkCodeType)) {
            checkCodeType = "siteCodeType";
        }
        // 查询的编码组 411327000,520300000
        String queryCheckCode = request.getParameter("queryCheckCode");
        if (StringUtils.isEmpty(queryCheckCode)) {
            return MsgResult.errorResult("查询条件区域/点位编码为空，查询失败。");
        }
        // 选择的区域编码字符串转换为数组
        String[] queryCheckCodeArr = queryCheckCode.split(",");
        // 选中区域编码数组转换为列表
        List<String> checkedCodeList = Arrays.asList(queryCheckCodeArr);

        // 空气质量因子:AQI,综合指数 compositeValue,PM10,PM25,SO2,NO2,CO,O3
        String qualityFactor = request.getParameter("qualityFactor");
        if (null == qualityFactor || "".equals(qualityFactor)) {
            // return MsgResult.infoResult("查询条件空气质量因子qualityFactor为空，查询失败。");
            qualityFactor = "AQI";
        }

        // 开始时间
        String startTime = request.getParameter("startTime");
        // startTime = "2017-02-15 15:00:00";
        if (StringUtils.isEmpty(startTime)) {
            return MsgResult.errorResult("查询条件开始时间startTime为空，查询失败。");
        }

        // 结束时间
        String endTime = request.getParameter("endTime");
        // endTime = "2017-02-16 12:00:00";
        if (StringUtils.isEmpty(endTime)) {
            return MsgResult.errorResult("查询条件结束时间endTime为空，查询失败。");
        }

        // 查询的表名（全称） T_DATA_AIR_HOUR
        String tableName = request.getParameter("tableName");
        if (StringUtils.isEmpty(tableName)) {
            return MsgResult.errorResult("查询条件表名为空，查询失败。");
        }

        // 封装request中的查询条件
        Map<String, Object> paraMap = new HashMap<String, Object>();

        paraMap.put("qualityFactor", qualityFactor);
        paraMap.put("startTime", startTime);
        paraMap.put("endTime", endTime);
        paraMap.put("tableName", tableName);

        try {
            if ("siteCodeType".equals(checkCodeType)) {
                paraMap.put("checkedSiteCodes", queryCheckCode);
                if (checkedCodeList.size() == 1) {
                    return airService.findAirQualitySingleSiteDataContrastThrend(paraMap);
                }
                return airService.findAirQualitySiteDataContrastThrend(paraMap);
            }
            paraMap.put("checkedRegionCodes", queryCheckCode);
            if (checkedCodeList.size() == 1) {
                return airService.findAirQualitySingleRegionDataContrastThrend(paraMap);
            }
            return airService.findAirQualityRegionDataContrastThrend(paraMap);
        } catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询空气质量数据对比趋势出现异常，后台程序异常。");
        }
    }

    /**
     * 根据区域编码、时间和表名查询出空气质量数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "findAirDataByTime", method = RequestMethod.GET)
    public MsgResult findAirDataByTime(HttpServletRequest request) {
        try {
            // 查询的编码组 B518091012,B518091011
            String queryCheckCode = request.getParameter("queryCheckCode");
            if (StringUtils.isEmpty(queryCheckCode)) {
                return MsgResult.errorResult("查询条件设备编码为空，查询失败。");
            }
            // 2017-06-22 20:00:00
            String startTime = request.getParameter("startTime");
            if (StringUtils.isEmpty(startTime)) {
                return MsgResult.errorResult("开始时间不能为空");
            }
            // 2017-06-23 20:00:00
            String endTime = request.getParameter("endTime");
            if (StringUtils.isEmpty(endTime)) {
                return MsgResult.errorResult("结束时间不能为空");
            }
            // 查询的表名（全称） T_DATA_SC_COLLECT_MIN5
            String tableName = request.getParameter("tableName");
            if (StringUtils.isEmpty(tableName)) {
                return MsgResult.errorResult("表名不能为空");
            }

            // 封装request中的查询条件
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("tableName", tableName);
            paraMap.put("queryCheckCode", queryCheckCode);
            paraMap.put("startTime", startTime);
            paraMap.put("endTime", endTime);

            List<Map> resultMap = airService.findAirDataByTime(paraMap);
            return MsgResult.okResult(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询空气质量原始数据信息异常,后台异常", e);
            return MsgResult.errorResult();
        }
    }

    /**
     * 导出5分钟空气质量数据Excel表格
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "airMointorDataReportExportExcel", method = RequestMethod.GET)
    public void airMointorDataReportExportExcel(HttpServletRequest request, HttpServletResponse response) {
        Workbook wb;
        try {
            // 查询的编码组 B518091012,B518091011
            String queryCheckCode = request.getParameter("queryCheckCode");
            if (StringUtils.isEmpty(queryCheckCode)) {
                queryCheckCode = "";
            }
            String tableName = request.getParameter("tableName");
            // 查询的表名，默认：T_DATA_SC_COLLECT_MIN5
            if (null == tableName || "".equals(tableName)) {
                tableName = "T_DATA_SC_COLLECT_MIN5";
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            // 开始时间
            String startTime = request.getParameter("startTime");
            startTime = null == startTime || "".equals(startTime)
                ? DateTimeUtil.getFormatDateStr(calendar.getTime(), DamConstant.SDF_YMD_HMS) : startTime;
            // 结束时间
            String endTime = request.getParameter("endTime");
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            endTime = null == endTime || "".equals(endTime)
                ? DateTimeUtil.getFormatDateStr(calendar.getTime(), DamConstant.SDF_YMD_HMS) : endTime;

            // 封装request中的查询条件
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("tableName", tableName);
            paraMap.put("startTime", startTime);
            paraMap.put("queryCheckCode", queryCheckCode);
            paraMap.put("endTime", endTime);
            List<Map> resultMap = airService.findAirDataByTime(paraMap);

            wb = ExcelUtil.fillAirMonitorDataExcelWithTemplate(resultMap, "monitorDataReportTemplate.xlsx",
                tableName + " " + startTime + "--" + endTime + "空气质量原始数据");

            ResponseUtil.export(response, wb, "Mongo空气质量原始数据.xlsx");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出空气质量原始Excel异常,后台异常", e);
        }

    }

    /**
     * 保存巡检设备信息
     * @author 李亚坤
     * @createtime 2017年7月18日14:55:59
     * @param request
     * @return
     */
    @RequestMapping(value = "/savePatrolDeviceInfo", method = RequestMethod.POST)
    public MsgResult savePatrolDeviceInfo(HttpServletRequest request) {
        try {
            return patrolDeviceService.savePatrolDeviceInfo(request);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("保存巡检设备异常");
        }
    }

    /**
     * 保存巡检设备 轨迹信息
     * @author 李亚坤
     * @createtime 2017年7月18日15:04:42
     * @param request
     * @return
     */
    @RequestMapping(value = "/savePatrolDeviceTrackData", method = RequestMethod.POST)
    public MsgResult savePatrolDeviceTrackData(HttpServletRequest request) {
        try {
            Map<String, Object> paramMap = wrapParams(request);
            return patrolDeviceService.savePatrolDeviceTrackData(request);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("保存巡检设备异常");
        }
    }


    /**
     * 根据设备编码查询设备信息
     * @author 李亚坤
     * @createtime 2017年7月18日15:54:52
     * @param request
     * @return
     */
    @RequestMapping(value = "/findPatrolDeviceInfoByDeviceCode", method = RequestMethod.GET)
    public MsgResult findPatrolDeviceInfoByDeviceCode(HttpServletRequest request) {
        try {
            return patrolDeviceService.findPatrolDeviceInfoByDeviceCode(request);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询巡检设备异常");
        }
    }

     /**
     * 根据设备编码查询设备巡检轨迹信息
     * @author 李亚坤
     * @createtime 2017年7月18日15:54:52
     * @param request
     * @return
     */
    @RequestMapping(value = "/findPatrolTrackByDeviceCode", method = RequestMethod.GET)
    public MsgResult findPatrolTrackByDeviceCode(HttpServletRequest request) {
        try {
            return patrolDeviceService.findPatrolTrackByDeviceCode(request);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询巡检设备异常");
        }
    }


}
